# -*- coding: utf-8 -*-
"""
惰性求值(lazy evaluation)：迭代器和生成器
"""

from math import pi
import logging

import py_global

logger = logging.getLogger(__name__)


def lazy_function(func):
    attr_name = '_lazy_' + func.__name__

    @property
    def _lazy_property(self):
        if not hasattr(self, attr_name):
            setattr(self, attr_name, func(self))
            pass
        return getattr(self, attr_name)

    return _lazy_property


class LazyClass(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, obj, cls):
        value = self.func(obj)
        setattr(obj, self.func.__name__, value)
        return value


class Circle(object):
    """求圆面积"""

    def __init__(self, radius):
        self.radius = radius

    # @LazyClass
    @lazy_function
    def area(self):
        logger.info(f'lazy evaluation:{self.__class__.__name__}')  # 只执行一次
        return pi * self.radius ** 2


if __name__ == '__main__':
    circle = Circle(2)
    print('Circle area:' + str(circle.area ** 2 + circle.area))
    pass
